package com.zjitc.rabbit;

import com.google.gson.Gson;
import com.rabbitmq.client.*;
import com.zjitc.dao.UserDao;

import com.zjitc.model.User;

import com.zjitc.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/29 0029
 * @description:
 */
public class GetRabbitMessage {
    private static Logger logger = Logger.getLogger(GetRabbitMessage.class);
    private Connection connection;
    String queueName;
    @Autowired
    UserDao userDao;
    @Autowired
    UserService userService;
    private Channel channel;

    public GetRabbitMessage() {
        ConnectionFactory factory = new ConnectionFactory();
        logger.debug("init.............GetRabbitMessage 35行");
        queueName = "getMail";
        factory.setHost("47.96.75.158");
        factory.setUsername("lhl");
        factory.setPassword("lhl");
        factory.setVirtualHost("lhl");
        try {
            this.connection = factory.newConnection();
            channel = this.connection.createChannel();
            channel.queueDeclare(queueName, true, false, false, null);
            logger.debug("connection.............GetRabbitMessage 45行");
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                                           AMQP.BasicProperties properties, byte[] body)
                        throws IOException {
                    String message = new String(body, "UTF-8");
                    logger.debug("message.............GetRabbitMessage 54行" + message);
                    String s = message.substring(0, 1);
                    Gson gson = new Gson();
                    String userU = "U";
                    if (s.equals(userU)) {
                        String s1 = message.substring(1);
                        User user = gson.fromJson(s1, User.class);
                        logger.debug("user.............GetRabbitMessage 69行" + message);
                        userService.register(user);
                        //也就是说向数据库添加成功后没有回来导致rabbitmq没有确认
                        logger.debug("try.............GetRabbitMessage 72行" + user);
                    }
//                    用户注册发邮件
//                    Gson gson=new Gson();
                    System.out.println(" [x] Received '" + message + "'");
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            channel.basicConsume(queueName, false, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
